package com.wonders.common.web.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wonders.framework.config.annotation.NotLogon;
import com.wonders.framework.util.JsonUtil;
import com.wonders.framework.util.web.RequestUtil;
import com.wonders.module.auth.entity.vo.UserVo;
import com.wonders.module.system.constant.SystemConstant;

/**
 * 登录拦截器
 * 
 * @author WuBin
 * 
 */
public class LogonInteceptor implements HandlerInterceptor {

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {

	}

	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2) throws Exception {
		HandlerMethod method = (HandlerMethod) arg2;
		// 对不含不需要登录注解的进行拦截
		if (method.getMethodAnnotation(NotLogon.class) == null
				&& method.getBean().getClass().getAnnotation(NotLogon.class) == null) {
			UserVo userVo = RequestUtil.getSessionAttr(SystemConstant.LOGON_USER,
					UserVo.class);
			if (userVo == null) {
				// 根据请求类型区分响应
				if (RequestUtil.isAjaxRequest()) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("success", false);
					map.put("type", "logon");
					RequestUtil.ajaxResponse(JsonUtil.toJson(map));
				} else {
					arg0.getRequestDispatcher("/index.jsp").forward(arg0, arg1);
				}
				return false;
			}
		}
		return true;
	}

}
